package com.studyyoun.android.nonghe.home.activity;
/**
 * Created by zhaolong on 2017/10/10.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidlongs.pullrefreshrecyclerylib.common.PullRecyclerViewUtils;
import com.androidlongs.pullrefreshrecyclerylib.inter.PullRecyclerViewLinserner;
import com.androidlongs.pullrefreshrecyclerylib.inter.PullRecyclerViewOnItemClickLinserner;
import com.androidlongs.pullrefreshrecyclerylib.model.PullRecyclerMoreStatueModel;
import com.studyyoun.android.androidcommonbaselibrary.activity.CommonBaseActivity;
import com.studyyoun.android.androidcommonbaselibrary.glide.CommonGlideUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.CommonLoadingUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.SharedPreferencesUtil;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.home.http.HomeHttpManager;
import com.studyyoun.android.nonghe.home.model.ArtModel;
import com.studyyoun.android.nonghe.home.model.CommonSearcherModel;
import com.studyyoun.android.nonghe.home.model.VideoModel;
import com.studyyoun.android.nonghe.http.HttpCallBackHelper;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * class infation
 */
public class SearchActivity extends CommonBaseActivity {

    private TextView mCancleTextView;
    private TextView mStartSearchTextView;
    private EditText mInputSearchEditText;
    private TextView mHistorySearchTextView;

    private String mCurrentSearcher ="android";
    private PullRecyclerViewUtils mPullRecyclerViewUtils;


    @Override
    protected void getAllIntentExtraDatas(Intent intent) {

    }

    @Override
    protected int getCommonLayoutId() {
        return R.layout.activity_search_layout;
    }

    @Override
    protected void commonInitView(View view) {

        mCancleTextView = findViewById(R.id.tv_cancle_sercher);
        mStartSearchTextView = findViewById(R.id.tv_start_search);
        mInputSearchEditText = findViewById(R.id.et_search_input);
        mHistorySearchTextView = findViewById(R.id.tv_search_history);


        RelativeLayout contentRelativeLayout = (RelativeLayout)findViewById(R.id.ll_search_main_content);

        //初始化
        mPullRecyclerViewUtils = PullRecyclerViewUtils.getInstance();


        //3初始化Recyclerview
        /**
         * 参数一 this Context实例
         * 参数二 单一布局模式条目布局ID
         * 参数三 数据集合
         * 参数四 回调监听
         */
        RelativeLayout relativeLayout = mPullRecyclerViewUtils.setRecyclerViewFunction(mContext, -1, mCommonArtModelList, mPullRecclerLinserner, mItemClickLinserner);

        //4相关设置

        //下拉刷新和上拉加载更多模式
        mPullRecyclerViewUtils.setRecyclerviewStatue(PullRecyclerViewUtils.RECYCLRYVIEW_STATUE.PULL_AND_UP);

        mPullRecyclerViewUtils.setFirstDefaultPageType(PullRecyclerViewUtils.SHOW_DEFAUTLE_PAGE_TYPE.NORMAL);

        //5将recyclerview添加到当前显示的页面中
        contentRelativeLayout.addView(relativeLayout);



    }

    @Override
    protected void commonFunction() {

    }

    @Override
    protected void commonDelayFunction() {

        final String search_history = SharedPreferencesUtil.getInstance(mContext).getData("search_history");
        mHistorySearchTextView.setText("最近：" + search_history);

        mCancleTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SearchActivity.this.finish();
            }
        });

        mStartSearchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String searchContent = mInputSearchEditText.getText().toString();
                if (TextUtils.isEmpty(searchContent)) {
                    ToastUtils.show("请输入要搜索的内容", mContext);
                    return;
                }

                mCommonArtModelList.clear();
                //保存
                SharedPreferencesUtil.getInstance(mContext).saveData("search_history", searchContent);
                mHistorySearchTextView.setText("最近：" + searchContent);
                mCurrentSearcher = searchContent;
                searchNetFunction(searchContent);

            }
        });
        mHistorySearchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String searchHistory = mHistorySearchTextView.getText().toString();
                if (!TextUtils.isEmpty(searchHistory)) {
                    mCurrentSearcher=search_history;
                    mInputSearchEditText.setText(search_history);
                    mCommonArtModelList.clear();
                    searchNetFunction(search_history);
                }
            }
        });

    }
    private PullRecyclerViewOnItemClickLinserner mItemClickLinserner=new PullRecyclerViewOnItemClickLinserner() {
        @Override
        public void setonItemClick(int position, int itemType, Object object) {
            PullRecyclerMoreStatueModel model = (PullRecyclerMoreStatueModel) object;
            itemType = model.itemType;
            if (itemType==1||itemType==4) {

                ArtModel artModel = (ArtModel) model.model;

                Intent intent = new Intent(SearchActivity.this, ArtDetaileActivity.class);
                intent.putExtra("artModel", artModel);
                SearchActivity.this.startActivity(intent);
            }else if(itemType==2||itemType==3) {
                VideoModel videoModel = (VideoModel) model.model;

                Intent intent = new Intent(SearchActivity.this, VideoDetaileActivity.class);
                intent.putExtra("videoModel", videoModel);
                SearchActivity.this.startActivity(intent);
            }
        }
    };
    private List<PullRecyclerMoreStatueModel> mCommonArtModelList = new ArrayList<>();
    private int mCurrentIndex = 0;
    private int mCurrentSize = 50;
    private int mType = 0;
    private SearchActivity.NetLoadingType mNetLoadingType = SearchActivity.NetLoadingType.DEFAULTlOADING;

    private enum NetLoadingType {
        UP_LOADING,
        PULL_LOADING,
        DEFAULTlOADING
    }
    private PullRecyclerViewLinserner mPullRecclerLinserner = new PullRecyclerViewLinserner() {
        @Override
        public void loadMoreData() {

            mCurrentIndex++;
            mNetLoadingType = SearchActivity.NetLoadingType.UP_LOADING;
            searchNetFunction(mCurrentSearcher);
        }

        @Override
        public void loadingRefresDataFunction() {
            mCurrentIndex = 0;
            mCommonArtModelList.clear();
            mNetLoadingType = SearchActivity.NetLoadingType.PULL_LOADING;
            searchNetFunction(mCurrentSearcher);
        }

        @Override
        public void setViewDatas(View itemView, int position, int itemType, Object object) {

            PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = (PullRecyclerMoreStatueModel) object;
            itemType = pullRecyclerMoreStatueModel.itemType;

            if (itemType == 1 || itemType == 4) {
                ArtModel artModel = (ArtModel) pullRecyclerMoreStatueModel.model;

                String artName = artModel.artName;
                TextView titleTextView = itemView.findViewById(R.id.tv_home_item_art_title);

                artName.replaceAll(mCurrentSearcher,"<font color='red' size='20'>"+mCurrentSearcher+"</font>");

                titleTextView.setText(Html.fromHtml(artName));
                titleTextView.setClickable(true);
                titleTextView.setMovementMethod(LinkMovementMethod.getInstance());


                String imageUrl = artModel.artImageUrl;
                ImageView imageView = itemView.findViewById(R.id.iv_home_item_art_img);
                imageUrl = HttpUrlHelper.BaseImageHost + imageUrl;
                CommonGlideUtils.showImageView(mContext, R.mipmap.default_pic, imageUrl, imageView);


                String artReadCount = artModel.artReadCount;
                TextView artReadCountTextView = itemView.findViewById(R.id.tv_home_item_art_read);
                artReadCountTextView.setText(artReadCount + "阅读");


                TextView artIsTopTextView = itemView.findViewById(R.id.tv_home_item_art_is_top);
                TextView artIsRecommendTextView = itemView.findViewById(R.id.tv_home_item_art_is_recommend);


                if (artModel.artIsTop == 1) {
                    artIsTopTextView.setVisibility(View.VISIBLE);
                } else {
                    artIsTopTextView.setVisibility(View.GONE);
                }

                if (artModel.artIsRecommend == 1) {
                    artIsRecommendTextView.setVisibility(View.VISIBLE);
                } else {
                    artIsRecommendTextView.setVisibility(View.GONE);
                }


            } else if (itemType == 2 || itemType == 3) {
                VideoModel videoModel = (VideoModel) pullRecyclerMoreStatueModel.model;


                String artName = videoModel.getTitle().trim();
                TextView titleTextView = itemView.findViewById(R.id.tv_home_item_art_title);
                artName.replaceAll(mCurrentSearcher,"<font color='red' size='20'>"+mCurrentSearcher+"</font>");
                titleTextView.setText(Html.fromHtml(artName));
                titleTextView.setClickable(true);
                titleTextView.setMovementMethod(LinkMovementMethod.getInstance());

                String imageUrl = videoModel.getImageUrl();
                ImageView imageView = itemView.findViewById(R.id.iv_home_item_art_img);
                imageUrl = HttpUrlHelper.BaseImageHost + imageUrl;
                CommonGlideUtils.showImageView(mContext, R.mipmap.default_pic, imageUrl, imageView);



                String artReadCount = String.valueOf(videoModel.readCount);
                TextView artReadCountTextView = itemView.findViewById(R.id.tv_home_item_art_read);
                artReadCountTextView.setText(artReadCount + "");


                List<String> articlPariseModels = videoModel.getPariseUserIdList();
                String artParise = "0";
                if (articlPariseModels != null) {
                    artParise = String.valueOf(articlPariseModels.size());
                }
                TextView artPariseCountTextView = itemView.findViewById(R.id.tv_home_item_art_pra);
                artPariseCountTextView.setText(artParise);


                TextView artIsTopTextView = itemView.findViewById(R.id.tv_home_item_art_is_top);
                TextView artIsRecommendTextView = itemView.findViewById(R.id.tv_home_item_art_is_recommend);


                if (videoModel.getVideoIsTop() == 1) {
                    artIsTopTextView.setVisibility(View.VISIBLE);
                } else {
                    artIsTopTextView.setVisibility(View.GONE);
                }

                if (videoModel.getVideoIsRecommend() == 1) {
                    artIsRecommendTextView.setVisibility(View.VISIBLE);
                } else {
                    artIsRecommendTextView.setVisibility(View.GONE);
                }

            }

        }
    };

    private void searchNetFunction(final String searchContent) {
        LogUtils.d("搜索 " + searchContent);

        CommonLoadingUtils.getInstance().showLoading(mCancleTextView);
        //Android相关的文章与视频
        //根据PageType来加载数据
        //视频
        HomeHttpManager.getInstance().getAllArtAndVideoListFromNameFunction(searchContent, mCurrentIndex, mCurrentSize, new HttpCallBackHelper<CommonSearcherModel>() {
            @Override
            public void onSuccess(final CommonSearcherModel commonSearcherModel) {



                CommonLoadingUtils.getInstance().closeFunction();

                List<ArtModel> articleModels = commonSearcherModel.articleModels;
                List<VideoModel> videoModels = commonSearcherModel.videoModels;




                if ((articleModels==null||articleModels.size()==0)&&(videoModels==null||videoModels.size()==0)) {

                    mPullRecyclerViewUtils.setLoadingDataList(null);
//                        mArtModelList.addAll(artModels);
//
//                        ExecutorFunction.getInstance().addRunnableTask(new Runnable() {
//                            @Override
//                            public void run() {
//                                for (ArtModel artModel : artModels) {
//                                    mArtSqlDBHelper.insertArt(artModel);
//                                }
//                            }
//                        });



                } else {
                    if(videoModels!=null||videoModels.size()>0){
                        for (VideoModel artModel : videoModels) {


                            PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = new PullRecyclerMoreStatueModel();
                            pullRecyclerMoreStatueModel.model = artModel;
                            pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_home_search_video_layout;
                            pullRecyclerMoreStatueModel.itemType = 3;

                            mCommonArtModelList.add(pullRecyclerMoreStatueModel);

                        }

                    }
                    if(articleModels!=null||articleModels.size()>0){
                        for (ArtModel artModel : articleModels) {

                            artModel.setArtName(artModel.getArtName().replaceAll("《","【"));
                            artModel.setArtName(artModel.getArtName().replaceAll("》","】"));


                            PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = new PullRecyclerMoreStatueModel();
                            pullRecyclerMoreStatueModel.model = artModel;
                            pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_home_search_art_layout;
                            pullRecyclerMoreStatueModel.itemType = 4;

                            mCommonArtModelList.add(pullRecyclerMoreStatueModel);

                        }

                    }

                    mPullRecyclerViewUtils.setLoadingDataList(mCommonArtModelList);
                }


            }

            @Override
            public void onFaile(String msg) {
                LogUtils.e("加载失败");
                CommonLoadingUtils.getInstance().closeFunction();

                switch (mNetLoadingType) {
                    case PULL_LOADING:
                        mCommonArtModelList.clear();
                        break;
                    case UP_LOADING:
                        mPullRecyclerViewUtils.setLoadingDataList(null);
                        return;
                    case DEFAULTlOADING:
                        mCommonArtModelList.clear();
                        break;
                }

//                    ExecutorFunction.getInstance().addRunnableTask(new Runnable() {
//                        @Override
//                        public void run() {
//
//                            List<ArtModel> artModels = mArtSqlDBHelper.queryArtModelList(mType);
//                            if (artModels.size() > 0) {
//                                for (ArtModel artModel : artModels) {
//
//                                    PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = new PullRecyclerMoreStatueModel();
//                                    pullRecyclerMoreStatueModel.model = artModel;
//                                    pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_home_art_layout;
//                                    pullRecyclerMoreStatueModel.itemType = 1;
//
//                                    mCommonArtModelList.add(pullRecyclerMoreStatueModel);
//
//                                }
//                                mHandler.post(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        pullRecyclerViewUtils.setLoadingDataList(mCommonArtModelList);
//                                    }
//                                });
//
//                            }
//                        }
//                    });
            }
        });
    }
}
